package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Value("${file.oss.prefix}")
    private String prefix;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private AuthorMapper authorMapper;

    @Autowired
    Configuration configuration;

    @Resource(name = "minIOFileStorageService")
    FileStorageService fileStorageService;

    @Override
    @Async
    public void generateArticlePage(Long articleId) {

        // 获取模板数据  authorApUserId  article  content
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleId));
        if (apArticleContent == null || StringUtils.isBlank(apArticleContent.getContent())) {
            log.error("文章内容为空，制作静态模板失败,articleId{}", articleId);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "文章内容为空，制作静态模板失败");
        }
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle == null) {
            log.error("文章为空，制作静态模板失败,articleId{}", articleId);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "文章为空，制作静态模板失败");
        }
        ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
        if (apAuthor == null) {
            log.error("作者为空，制作静态模板失败,articleId{}", articleId);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "作者为空，制作静态模板失败");
        }

        Map map = new HashMap();
        map.put("article", apArticle);
        map.put("authorApUserId", apAuthor.getUserId());
        List<Map> list = JSONArray.parseArray(apArticleContent.getContent(), Map.class);
        map.put("content", list);

        try {
            // freemarker 模板制作
            Template template = configuration.getTemplate("article.ftl");
            // 将map变为输出流
            StringWriter stringWriter = new StringWriter();
            template.process(map, stringWriter);
            // 封装输入流，生产minio静态路径
            InputStream in = new ByteArrayInputStream(stringWriter.toString().getBytes());
            String url = fileStorageService.store(prefix, articleId + ".html", "text/html", in);
            log.info("文件路径生成完毕，路径为：{}", url);
            //修改路径
            apArticle.setStaticUrl(url);
            apArticleMapper.updateById(apArticle);


        } catch (Exception e) {
            e.printStackTrace();
            log.error("文章详情静态页生成失败=====>articleId : {}    ========> {}",articleId,e.getCause());
        }


    }
}
